/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: smvc2022 - ApiController
 * <p>Powered by webrx On 2022-04-06 16:22:24
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@RestController
@CrossOrigin
@RequestMapping("/api")
public class ApiController {
    @PostMapping("u6")
    public Map<String, Object> upload(MultipartFile file, String user, HttpServletRequest req) {
        Map<String, Object> map = new HashMap<String, Object>();
        String msg = "上传失败，请选择一个文件";
        if (file.isEmpty()) {
            map.put("code", 401);
            msg = "上传失败，请选择一个文件";
            map.put("msg",msg);
        } else {
            try {
                String filename = file.getOriginalFilename();
                String fileext = filename.lastIndexOf(".") == -1 ? "" : filename.toLowerCase().substring(filename.lastIndexOf("."));
                long filesize = file.getSize();
                String path = req.getServletContext().getRealPath(String.format("uploads/%tY%<tm", System.currentTimeMillis()));
                File dst = new File(path);
                if (!dst.exists()) dst.mkdirs();
                msg = "上传成功，文件：'" + filename + "'";
                map.put("code", 200);
                map.put("msg","上传成功："+filename);
                map.put("author",user);
                file.transferTo(new File(path, filename));
            } catch (IOException e) {
                msg = "上传失败，未知错误";
                map.put("code", 402);
                map.put("msg",msg);
            }
        }
        return map;
    }
}
